package logintest.util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FirstFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }
    @Override  //请求和响应时都会执行这个方法
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //设置编码
        request.setCharacterEncoding("utf-8");
        //防止用户在未登陆的情况下访问登陆页面
        String requestURI = request.getRequestURI();
        Object uname = request.getSession().getAttribute("uname");
        if (requestURI.endsWith("success.jsp")&&uname == null){
            response.sendRedirect("/login.jsp");
        }
        //调取下一个过滤器或者调取servlet
        filterChain.doFilter(servletRequest,servletResponse);
    }
    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}
